#include <QMessageBox>

#include "customrelationmodel.h"

CustomRelationModel::CustomRelationModel(QObject *parent, QSqlDatabase db):
        QSqlRelationalTableModel(parent, db)
{
}

void CustomRelationModel::setTable(const QString &tableName)
{    
    QSqlRelationalTableModel::setTable(tableName);
    QSqlQuery query(this->database());
    QString sql = "select * from getrelation('%1')";
    sql = sql.arg(tableName);    
    query.prepare(sql);

    if(query.exec())
    {
        while(query.next())
        {
            int colindex = record().indexOf(query.value(query.record().indexOf("basefield")).toString());
            setRelation(colindex, QSqlRelation(query.value(query.record().indexOf("reltable")).toString(),
                                               query.value(query.record().indexOf("relpkey")).toString(),
                                               query.value(query.record().indexOf("relfield")).toString()
                                               ));
        }
    }
    else
        QMessageBox::information(0, "error", query.lastError().text());
}
